import React, { useEffect, useState } from 'react'
import { Card, Select, Input, Button, Table, message } from 'antd';
import { SearchOutlined, PlusCircleOutlined } from '@ant-design/icons'
import { useHistory } from 'react-router-dom'
import ajax from '../../service/ajax'
import { PAGE_SIZE } from '../../config/constants'

const { Option } = Select

export default function Product() {
  const [productList, setProductList] = useState([]) // 商品列表
  const [pages, setPages] = useState() // 总页数
  const [total, setTotal] = useState() // 商品数据的总条数
  const [isLoading, setIsLoading] = useState(false)
  const [isSearch, setIsSearch] = useState(false)
  const [searchType, setSearchType] = useState('productName') // 搜索类型
  const [searchWords, setSearchWords] = useState('')
  const [currentPage, setCurrentPage] = useState(1)

  const history = useHistory()

  const columns = [
    {
      title: '商品名称',
      dataIndex: 'name',
      width: '18%',
      key: 'name',
      align: 'center'
    },
    {
      title: '商品描述',
      dataIndex: 'desc',
      key: 'desc',
      align: 'center'
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      width: '9%',
      align: 'center',
      render: price => '￥' + price
    },
    {
      title: '状态',
      // dataIndex: 'status',
      key: 'status',
      width: '10%',
      align: 'center',
      render: (item) => (
        <div>
          <Button
            onClick={() => changeProdStatus(item)}
            type={item.status === 1 ? 'danger' : 'primary'}
          >
            {item.status === 1 ? '下架' : '上架'}
          </Button><br />
          <span>{item.status === 1 ? '在售' : '已停售'}</span>
        </div>
      )
    },
    {
      title: '操作',
      dataIndex: '_id',
      key: 'operation',
      width: '10%',
      align: 'center',
      render: (id) => (
        <div>
          <Button 
            type="link"
            onClick={() => history.push(`/admin/prod_about/product/detail/${id}`)}
          >
            详情
          </Button>
          <br />
          <Button 
            type="link"
            onClick={() => history.push(`/admin/prod_about/product/update/${id}`)}
          >
            修改
          </Button>
        </div>
      )
    },
  ];

  useEffect(() => {
    getProductList()
  }, [isSearch])

  // 上架和下架
  const changeProdStatus = async ({ _id, status }) => {
    console.log(_id, status)
    let result = await ajax.post('/manage/product/updateStatus', { productId: _id, status })
    const { msg } = result
    const _status = result.status
    if (_status === 0) {
      message.success('操作成功')
      const arr = [...productList]
      console.log(arr)
      arr.forEach((item) => {
        if (item._id === _id) {
          if (status === 1) {
            item.status = 2
          } else {
            item.status = 1
          }
        }
      })

      setProductList(arr)
    } else {
      message.error(msg)
    }

  }


  // 分页请求数据
  const getProductList = async (pageNum = 1) => {
    setIsLoading(true)
    let result
    if (isSearch) {
      result = await ajax('/manage/product/search', { params: { [searchType]: searchWords, pageNum, pageSize: PAGE_SIZE } })
    } else {
      result = await ajax('/manage/product/list', { params: { pageNum, pageSize: PAGE_SIZE } })
    }

    const { data, msg, status } = result
    if (status === 0) {
      setIsLoading(false)
      const { list, pages, total } = data
      setProductList(list)
      setPages(pages)
      setTotal(total)
      setCurrentPage(pageNum)
    } else {
      message.error(msg)
      setIsLoading(false)
    }
  }

  const search = () => {
    setIsSearch(true)
    getProductList()
  }

  return (
    <Card
      title={
        <div>
          <Select onChange={(value) => setSearchType(value)} defaultValue={searchType}>
            <Option value="productName">按名称搜索</Option>
            <Option value="productDesc">按描述搜索</Option>
          </Select>
          <Input
            onChange={e => setSearchWords(e.target.value)}
            allowClear
            style={{ marginLeft: 10, marginRight: 10, width: '20%' }}
          />
          <Button type="primary" onClick={() => { search() }}><SearchOutlined />搜索</Button>
        </ div>
      }
      extra={
        <Button 
          type="primary"
          onClick={() => history.push('/admin/prod_about/product/add')}
        >
          <PlusCircleOutlined />添加商品
        </Button>}
    >
      <Table
        dataSource={productList}
        columns={columns}
        loading={isLoading}
        bordered
        rowKey="_id"
        pagination={{
          pageSize: 4,
          total: total,
          current: currentPage,
          onChange: (page) => getProductList(page)
        }}
      />
    </Card>
  )
}